package com.sharainy.contoller;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.sharainy.pojo.Merchant;
import com.sharainy.pojo.Report;
import com.sharainy.pojo.Settlement;
import com.sharainy.pojo.User;
import com.sharainy.service.MerchantService;
import com.sharainy.service.SettlementService;
import com.sharainy.util.AlipayConfig;
import com.sharainy.util.DateUtil;
import com.sharainy.util.RestResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

@Controller
@RequestMapping("/report")
public class ReportController {
    @Autowired
    private MerchantService merchantService;
    @Autowired
    private SettlementService settlementService;
    @RequestMapping(value = "/reportByComsPage")
    public String index(){
        return "reportByComs";
    }
    @RequestMapping(value = "/reportByTypePage")
    public String index2(){
        return "reportByType";
    }
    @RequestMapping("/getSettlementSum")
    @ResponseBody
    public RestResponse getReceiptMsg(String ym, Integer page, Integer limit, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (page==null){page=1;}
        if (limit==null){limit=10;}
        Map<String, String> map = new HashMap<String, String>();
        JSONObject jsonMain = new JSONObject();
        if (ym==null||"".equals(ym)){
            ym= DateUtil.getSysYearMonth();
        }
        map.put("ym",ym.replaceAll("-",""));
        Report elecReport = new Report();
        elecReport.setName("电");
        Report waterReport = new Report();
        waterReport.setName("水");
        Report gasReport = new Report();
        gasReport.setName("气");
        List<Merchant> merchantList = merchantService.selectAllMerchant(user.getCompanyid()+"");
        for (Merchant merchant:merchantList) {
            map.put("merchantId",merchant.getId()+"");
            System.out.println("--"+merchant.getId());
            List<Settlement> settlements = settlementService.selectSettlementById(map);
            for (Settlement settlement:settlements) {
                elecReport.setUsage(DateUtil.add(elecReport.getUsage(),settlement.getElecusage()));
                elecReport.setCost(DateUtil.add(elecReport.getCost(),settlement.getEleccost()));
                waterReport.setUsage(DateUtil.add(waterReport.getUsage(),settlement.getWaterusage()));
                waterReport.setCost(DateUtil.add(waterReport.getCost(),settlement.getWatercost()));
                gasReport.setUsage(DateUtil.add(gasReport.getUsage(),settlement.getGasusage()));
                gasReport.setCost(DateUtil.add(gasReport.getCost(),settlement.getGascost()));
            }
        }
        List<Report> reportList = new ArrayList<Report>();
        reportList.add(elecReport);
        reportList.add(waterReport);
        reportList.add(gasReport);
        jsonMain.put("reportList",reportList);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }

    @RequestMapping("/getMerchantMonthData")
    @ResponseBody
    public RestResponse getMerchantMonthData(String ym, Integer page, Integer limit, HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (page==null){page=1;}
        if (limit==null){limit=10;}
        Map<String, String> map = new HashMap<String, String>();
        JSONObject jsonMain = new JSONObject();
        if (ym==null||"".equals(ym)){
            ym= DateUtil.getSysYearMonth();
        }
        map.put("ym",ym.replaceAll("-",""));
       Map<String,Settlement> settlementMap = new HashMap<String, Settlement>();
        List<Merchant> merchantList = merchantService.selectAllMerchant(user.getCompanyid()+"");
        for (Merchant merchant:merchantList) {
            Settlement settlement = new Settlement();
            settlement.setMerchantid(merchant.getId());
            settlement.setMerchantname(merchant.getName());
            settlementMap.put(String.valueOf(merchant.getId()),settlement);
        }
        for (Merchant merchant:merchantList) {
            map.put("merchantId",merchant.getId()+"");
            System.out.println("--"+merchant.getId());
            List<Settlement> settlements = settlementService.selectSettlementById(map);
            if (settlements!=null) {
                for (Settlement settlement2 : settlements) {;
                    Settlement settle = settlementMap.get(settlement2.getMerchantid()+"");
                    settle.setElecusage(DateUtil.add(settle.getElecusage(), settlement2.getElecusage()));
                    settle.setEleccost(DateUtil.add(settle.getEleccost(), settlement2.getEleccost()));
                    settle.setWaterusage(DateUtil.add(settle.getWaterusage(), settlement2.getWaterusage()));
                    settle.setWatercost(DateUtil.add(settle.getWatercost(), settlement2.getWatercost()));
                    settle.setGasusage(DateUtil.add(settle.getGasusage(), settlement2.getGasusage()));
                    settle.setGascost(DateUtil.add(settle.getGascost(), settlement2.getGascost()));
                    if (settlement2.getNowtime() > settle.getNowtime()) {
                        settle.setNowtime(settlement2.getNowtime());
                        settle.setAftersettle(settlement2.getAftersettle());
                    }

                }
            }
        }
        List<Settlement> searchSettlementList = new ArrayList<Settlement>();
        settlementMap.forEach((key, value) -> {
            searchSettlementList.add(value);
        });
        jsonMain.put("settlementList",searchSettlementList);
        RestResponse restResponse = RestResponse.succuess();
        restResponse.setData(jsonMain);
        return restResponse;
    }

    /**
     *
     * @Title: AlipayController.java
     * @Package com.sihai.controller
     * @Description: 支付宝异步 通知页面
     * Copyright: Copyright (c) 2017
     * Company:FURUIBOKE.SCIENCE.AND.TECHNOLOGY
     *
     * @author sihai
     * @date 2017年8月23日 下午8:51:13
     * @version V1.0
     */
    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public void alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {

        System.out.println("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的outtradeno是否为商户系统中创建的订单号，
		2、判断totalamount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的sellerid（或者selleremail) 是否为outtradeno这笔单据的对应的操作方（有的时候，一个商户可能有多个sellerid/selleremail）
		4、验证appid是否为该商户本身。
		*/
        if(signVerified) {//验证成功
            //商户订单号
            String outtradeno = new String(request.getParameter("outtradeno").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String tradeno = new String(request.getParameter("tradeno").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String tradestatus = new String(request.getParameter("tradestatus").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String totalamount = new String(request.getParameter("totalamount").getBytes("ISO-8859-1"),"UTF-8");

            if(tradestatus.equals("TRADEFINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（outtradeno）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (tradestatus.equals("TRADESUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（outtradeno）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
               // orderService.updateOrderStatus(outtradeno, tradeno, totalamount);

                //Orders order = orderService.getOrderById(outtradeno);
                //Product product = productService.getProductById(order.getProductId());

                System.out.println("********************** 支付成功(支付宝异步通知) **********************");
                System.out.println("* 订单号: {}"+outtradeno);
                System.out.println("* 支付宝交易号: {}"+tradeno);
                System.out.println("* 实付金额: {}"+totalamount);
                System.out.println("***************************************************************");
            }
            System.out.println("支付成功...");

        }else {//验证失败
            System.out.println("支付, 验签失败...");
        }

    }
}
